﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ScrumSim
{
    public class Animation
    {
        private string mName;

        private AnimatedGameObject mOwner;

        private Texture2D mSpriteSheet;
        private Rectangle mSubRect;

        private int mNbFrames;
        private int mCurrentFrame;

        private float mSpeed;
        private float mTimeByFrame;
        private float mTimeSinceLastChange;

        private bool mLoop;

        //--------------------------------

        public Animation(AnimatedGameObject pOwner, string pName, Texture2D pSpriteSheet, Rectangle pSubRect, float pSpeed, int pNbFrames, bool pLoop = true)
        {
            mName = pName;

            mOwner = pOwner;

            mLoop = pLoop;

            mCurrentFrame = 0;
            mNbFrames = pNbFrames;

            mSpeed = pSpeed;
            mTimeByFrame = mSpeed / (float)mNbFrames;

            mTimeSinceLastChange = 0;

            mSpriteSheet = pSpriteSheet;
            mSubRect = pSubRect;
        }

        //--------------------------------

        public void Play()
        {
            mCurrentFrame = 0;
            mTimeSinceLastChange = 0;
            mOwner.sprite = mSpriteSheet;
            mOwner.subrect = mSubRect;
        }

        //--------------------------------

        public void Update(float pDelta)
        {
            mTimeSinceLastChange += pDelta;

            bool mWasChanged = false;

            while (mTimeSinceLastChange > mTimeByFrame)
            {
                mCurrentFrame++;
                mWasChanged = true;

                if (mCurrentFrame >= mNbFrames)
                {
                    if (mLoop)
                        mCurrentFrame = 0;
                    else
                    {
                        mCurrentFrame = mNbFrames - 1;
                        mWasChanged = false;
                    }
                }

                mTimeSinceLastChange -= mTimeSinceLastChange;
            }

            if (mWasChanged)
            {
                Rectangle lRect = mSubRect;
                lRect.X += lRect.Width * mCurrentFrame;
                mOwner.subrect = lRect;
            }
        }
    }
}
